import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import BuyerHome from '../views/BuyerHome.vue'
import BuyerOrders from '../views/BuyerOrders.vue'
import SellerHome from '../views/SellerHome.vue'
import AdminHome from '../views/AdminHome.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/buyer',
    name: 'BuyerHome',
    component: BuyerHome
  },
  {
    path: '/buyer/orders',
    name: 'BuyerOrders',
    component: BuyerOrders
  },
  {
    path: '/seller',
    name: 'SellerHome',
    component: SellerHome
  },
  {
    path: '/admin',
    name: 'AdminHome',
    component: AdminHome,
    meta: { requiresAdmin: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 如果是登录或注册页面，直接放行
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    try {
      // 这里可以添加检查用户是否为管理员的逻辑
      // 由于前端无法直接获取用户信息，我们让组件内部处理权限检查
      next()
    } catch (error) {
      ElMessage.error('权限不足，请重新登录')
      next('/login')
    }
  } else {
    next()
  }
})

export default router